#!/usr/bin/perl -w

#########################################################################################################
# Options - Optional
#########################################################################################################
my $numdays = shift;

#########################################################################################################
# Program Modules
#########################################################################################################
use XML::Simple;
use Data::Dumper;
use DBI;
use LWP::UserAgent;

#########################################################################################################
# Program Variables
#########################################################################################################
use FindBin qw($Bin);
use lib "$Bin";
use config;

#########################################################################################################
# Program Start
#########################################################################################################
if (&read_config_option("controller_type") ne "Apex") {

    # Not running an Apex controller, or it's not configured, abort
    exit 100;
}

my $controller_url = &read_config_option("controller_url") . "/cgi-bin/outlog.xml";

# If we have been told a number for how many previous days, grab all the available records.
if (defined($numdays)) {

    #my $req = HTTP::Request->new(GET => 'http://172.29.0.50/cgi-bin/datalog.xml?sdate=120220&days=10');
    $prevdate       = `date "+%y%m%d" --date="-$numdays days"`;
    $controller_url = &read_config_option("controller_url") . "/cgi-bin/datalog.xml?sdate=$prevdate&days=$numdays";
}

my $xmlcontent;

# Program Start
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1 ");
$ua->timeout("3000");

# Create a request
my $req = HTTP::Request->new(GET => $controller_url);

# Pass request to the user agent and get a response back
my $res = $ua->request($req);

# Check the outcome of the response
if ($res->is_success) {
    $xmlcontent = $res->content;
    print "Apex data retrieved.\n";
} else {
    print $res->status_line, "\n";
    exit 100;
}

#my $xml		= new XML::Simple;
#print Dumper($xmlcontent);

my @testarray = split("\n", $xmlcontent);

my %datahash;
my $date  = "";
my $name  = "";
my $value = "";

foreach $line (@testarray) {

    if ($line =~ m/<date>(\d\d)\/(\d\d)\/(\d\d\d\d) (.*)<\/date>/i) {
        my $month = $1;
        my $day   = $2;
        my $year  = $3;
        my $time  = $4;

        $date = "$year-$month-$day $time";
    } elsif ($line =~ m/<name>(.*)<\/name>/i) {
        $name = $1;
    } elsif ($line =~ m/<value>(.*)<\/value>/i) {
        my $setting = $1;

        if ($setting eq "ON") {
            $value = 1;
        } else {
            $value = 0;
        }

        $datahash{$date}{name}  = $name;
        $datahash{$date}{value} = $value;

        # Clear values
        $date  = "";
        $name  = "";
        $value = "";
    }
}

my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");

foreach $date (sort keys %datahash) {
    if ($debug == 1) {
        print "At $date, $datahash{$date}{name} was set $datahash{$date}{value}.\n";
    }

    print "Checking $date for outlet $datahash{$date}{name} ... ";

    my $hash_ref = $dbh->selectrow_hashref("SELECT * FROM outlet WHERE collection_time=datetime(?) AND name=?", undef, $date, $datahash{$date}{name});

    if (!defined($hash_ref)) {
        my $sql = "INSERT INTO outlet (collection_time, name, value) VALUES (datetime(?), ?, ?);";
        $dbh->do($sql, undef, $date, $datahash{$date}{name}, $datahash{$date}{value}) or warn;
        print "added to db.\n";
    } else {
        print "already in db.\n";
    }
}

$dbh->disconnect;

exit 0;

